const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const hostConfig = require('./src/host.config.js').host
const CleanDist = require('clean-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();

var cdnPrefix = '',
    buildPath = '',
    publishPath,
    indexPath = '';

var nodeEnv = process.env.NODE_ENV;

if (nodeEnv == 'local') {
    cdnPrefix = hostConfig.LOCALHOST_Prefix;
    buildPath = 'dist/';
    indexPath = '../';
}else if (nodeEnv == 'test') {
    cdnPrefix = hostConfig.TEST_Prefix;
    buildPath = 'test/';
}else if(nodeEnv == 'release'){
    cdnPrefix = hostConfig.RELEASE_Prefix;
    buildPath = 'release/';
} else if (nodeEnv == 'online') {
    buildPath = 'online/';
    cdnPrefix = hostConfig.ONLINE_Prefix;
} else {
    indexPath = '../';
    buildPath = 'dist/';
    cdnPrefix = hostConfig.LOCALHOST_Prefix;
}

publishPath = cdnPrefix + buildPath;

console.log('当前环境:[' + (nodeEnv || '本地') + ']\n当前路径:[' + publishPath + ']\n编译开始......');

function resolve (dir) {
    return path.join(__dirname, dir)
}

module.exports = smp.wrap({
    devtool:'cheap-module-eval-source-map',
    entry: {
        app: ['./src/main.js'],
        vender: ['./src/js/common.js']
    },
    externals: {
        vue: "window.Vue",
        'vue-router':"window.VueRouter",
        'axios':"window.axios",
        'element-ui': 'window.ELEMENT'
    },
    output: {
        path: resolve(buildPath),
        publicPath: cdnPrefix,
        filename: '[name].js?[hash]',
        chunkFilename: '[id][chunkhash].js'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    postcss: [
                        require('precss'),
                        require('autoprefixer')
                      ],
                    loaders: {
                        'scss': 'vue-style-loader!css-loader!sass-loader',
                        'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
                    }
                }
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },

            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader', 'sass-loader']
                })
            },
            {
                test: /\.css$/,
                use: [
                    { loader: "style-loader" },
                    { loader: "css-loader" },
                    { loader: "postcss-loader" }
                ]
            },
            {
                test: /\.(png|jpg|gif|woff|eot|svg|ttf)$/,
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]?[hash]'
                }
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: indexPath+'index.html',
            template: 'template.html'
        }),
        new ExtractTextPlugin('static/style.css?[hash]'),


    ],
    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
            '@': resolve('src'),
            'vue$': 'vue/dist/vue.esm.js',
            'components': resolve('src/components'),
            'js':resolve('src/js')
        }
    },
    devServer: {
        host: 'felsass.jinghao.com',
        historyApiFallback: true,
        noInfo: true,
        hot: true,
        proxy: {
            '/api/*': {
                target: 'http://felsass.jinghao.com',
                changeOrigin: true,
                secure: false
            }
        },
    },

    performance: {
        hints: false
    }
})

// if(nodeEnv == 'development') {
//     module.exports.plugins = (module.exports.plugins || []).concat([
//         new BundleAnalyzerPlugin({
//             analyzerMode: 'server',
//             analyzerHost: '127.0.0.1',
//             analyzerPort: 8888,
//             reportFilename: 'report.html',
//             defaultSizes: 'parsed',
//             openAnalyzer: true,
//             generateStatsFile: false,
//             statsFilename: 'stats.json',
//             logLevel: 'info'
//         })
//     ]);
// }

if(nodeEnv != 'local'){
    module.exports.plugins = (module.exports.plugins || []).concat([
        new CopyWebpackPlugin([
            {
                from: path.resolve(__dirname, 'static/**/*'),
                toType: 'dir'
            }
        ])
    ]);
}

if (nodeEnv == 'online' || nodeEnv == 'test') {
    module.exports.devtool = 'cheap-module-source-map'
    module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false,
                drop_debugger: true,
                drop_console: true
            }
        }),
        new webpack.LoaderOptionsPlugin({
            minimize: true
        }),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vender'
        }),

        new CleanDist(['test', 'online'])

    ])
}

